from django.conf import settings
from django.core.files.storage import Storage
from django.utils.deconstruct import deconstructible
import oss2


@deconstructible
class AliOSSStorage(Storage):
    """
    自定义的文件保存Storage实现类
    不断完善中...
    """

    def __init__(self, access_key_id=None, access_key_secret=None, endpoint=None, bucket_name=None, connect_timeout=30):
        """

        Args:
            access_key_id: 阿里OSS账号AccessKe
            access_key_secret: OSS认证秘钥
            endpoint: 访问端点(前缀)
            bucket_name: 文件保存的桶(容器)
            connect_timeout: 连接超时
        """
        if not access_key_id:
            self.access_key_id = settings.ACCESS_KEY_ID
        if not access_key_secret:
            self.access_key_secret = settings.ACCESS_KEY_SECRET
        if not endpoint:
            self.endpoint = settings.ENDPOINT
        if not bucket_name:
            self.bucket_name = settings.BUCKET_NAME
        if hasattr(settings, 'CONNECT_TIMEOUT'):
            self.connect_timeout = settings.CONNECT_TIMEOUT
        else:
            self.connect_timeout = connect_timeout
        # 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录RAM控制台创建RAM账号。
        self.auth = oss2.Auth(self.access_key_id, self.access_key_secret)
        # Endpoint以杭州为例 https://oss-cn-hangzhou.aliyuncs.com，其它Region请按实际情况填写。
        self.bucket = oss2.Bucket(self.auth, self.endpoint, self.bucket_name, connect_timeout=self.connect_timeout)

    def _save(self, name, content):
        rs = self.bucket.put_object(name, content)
        return name if rs.status == 200 else None

    def path(self, name):
        pass

    def delete(self, name):
        pass

    def exists(self, name):
        pass

    def listdir(self, path):
        pass

    def size(self, name):
        pass

    def url(self, name):
        """

        Args:
            name: 数据库中保存的文件名

        Returns: 完整的URL

        """
        return f'https://{self.bucket_name}.{self.endpoint[8:]}/{name}' \
            if self.endpoint.startswith('https://') \
            else self.bucket.sign_url('GET', name, 200)

    def get_accessed_time(self, name):
        pass

    def get_created_time(self, name):
        pass

    def get_modified_time(self, name):
        pass
